package com.jin.crud.common.config.security;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jin.crud.bean.LoginUser;
import com.jin.crud.bean.SysUser;
import com.jin.crud.common.code.ResultCode;
import com.jin.crud.common.code.UserStatus;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.service.SysPermissionService;
import com.jin.crud.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @Author yuxuejin
 * @Date 2021/11/25 21:26
 * @Description: 自定义用户登录认证逻辑
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserAccount(username);
        if (ObjectUtils.isEmpty(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ResultException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(), ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ResultException(ResultCode.USER_ACCOUNT_DELETED.getCode(), ResultCode.USER_ACCOUNT_DELETED.getMessage());
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ResultException(ResultCode.USER_ACCOUNT_DEACTIVATE.getCode(), ResultCode.USER_ACCOUNT_DEACTIVATE.getMessage());
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user, permissionService.getMenuPermission(user));
    }

}
